package com.java.star.novel.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.star.novel.core.bean.Result;
import com.java.star.novel.entity.CommentReply;
import com.java.star.novel.mapper.CommentReplyMapper;
import com.java.star.novel.no.to.ReplyAddTO;
import com.java.star.novel.service.CommentReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.java.star.novel.core.enums.ResultCode.FAIL2;

/**
 * <p>
 * 评论回复表 服务实现类
 * </p>
 *
 * @author 零限Lx
 * @since 2023-07-13
 */
@Service
public class CommentReplyServiceImpl extends ServiceImpl<CommentReplyMapper, CommentReply> implements CommentReplyService {

    @Autowired
    private CommentReplyMapper commentReplyMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addCommentReply(Long novelId, Long commentId, ReplyAddTO replyAddTO) throws Exception {

        // 根据评论id查询用户回复该评论的总次数
        int replyCount = commentReplyMapper.countRepliesByCommentId(commentId);
        if (replyCount >= 30) {
            return new Result().code(FAIL2);// code：502 msg：最多只能回复30条评论
        }

        // 创建一个新的回复对象
        CommentReply reply = new CommentReply();
        reply.setCommentId(commentId);
        // 假设在这里获取当前用户的ID，这里以假设值1为例
        Long currentUserId = 1L;
        reply.setUserId(currentUserId);
        reply.setContent(replyAddTO.getReplyContent());

        // 保存回复信息
        commentReplyMapper.insert(reply);

        // 更新评论的回复数
        this.baseMapper.incrementReplyCount(commentId);
        return Result.ok();

    }

}

